package com.example.weight.householdWaste;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.network.OkHttp;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

//import okhttp3.MediaType;
//import okhttp3.OkHttpClient;

public class FacilityMaintainPlanActivity extends AppCompatActivity {

    private SharedPreferences preferences;

    private ItemAdapter adapter;
    private List<String> nameList;

    private EditText checkResult, comment;

    private PopupWindow popupWindow;

    private String name, role, repairMethod, formId, factory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_facility_maintain_plan);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        checkResult = findViewById(R.id.facility_maintain_plan_check_result);
        comment = findViewById(R.id.facility_maintain_plan_comment);

        if (role.equals("检查人")) {
            // 当登录人为检查人，获取设备名称和保养方法，检查人填写检查结果
            RequestQueue queue = Volley.newRequestQueue(this);
            String url = Config.url + "/shlj/equipmentMaintenance/getlatest";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("zys", response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                JSONObject data = jsonObject.getJSONObject("data");
                                if (!data.isNull("result")) {
                                    String result = data.getString("result");
                                    String remarks = data.getString("remarks");
                                    checkResult.setText(result);
                                    comment.setText(remarks);
                                    formId = data.getString("id");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(FacilityMaintainPlanActivity.this,
                            "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> map=new HashMap<>();
                    map.put("equipmentName", "液压步进式给料机");
                    map.put("maintenanceContent", "固定轴承");
                    map.put("factory", factory);
                    return map;
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(stringRequest);
        } else {
            // 当登录人是操作人，禁用“检查结果”输入框
            checkResult.setFocusableInTouchMode(false);
            checkResult.clearFocus();
            // 提示用户今日是否已填过此表
            RequestQueue queue = Volley.newRequestQueue(this);
            String url = Config.url + "/shlj/equipmentMaintenance/getlast" + "?factory=" + factory;
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                JSONObject data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id")) {
                                    Toast.makeText(FacilityMaintainPlanActivity.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(FacilityMaintainPlanActivity.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(stringRequest);
        }

        TitleBar titleBar = findViewById(R.id.facility_maintain_plan_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                FacilityMaintainPlanActivity.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        Spinner maintainContent = findViewById(R.id.facility_maintain_plan_maintain_content);
        maintainContent.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] maintainContents = getResources().getStringArray(
                        R.array.householdWaste_facilityMaintainPlan);
                repairMethod = maintainContents[position];

                if (role.equals("检查人")) {
                    String facilityName = repairMethod.split(" ")[0];
                    String repairContent = repairMethod.split(" ")[1];
                    RequestQueue queue = Volley.newRequestQueue(FacilityMaintainPlanActivity.this);
                    String url = Config.url + "/shlj/equipmentMaintenance/getlatest";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("zys", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        JSONObject data = jsonObject.getJSONObject("data");
                                        if (!data.isNull("result")) {
                                            String result = data.getString("result");
                                            String remarks = data.getString("remarks");
                                            checkResult.setText(result);
                                            comment.setText(remarks);
                                            formId = data.getString("id");
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                    "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipmentName", facilityName);
                            map.put("maintenanceContent", repairContent);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }

                Toast.makeText(FacilityMaintainPlanActivity.this,
                        "你点击的是:"+maintainContents[position], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // 设置输入记录缓存
        preferences = getSharedPreferences("facility_maintain_plan", Context.MODE_PRIVATE);

        nameList = new ArrayList<>(preferences.getStringSet("checkResult", new HashSet<>()));
        List<Item> itemList = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : nameList) {
            itemList.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        adapter = new ItemAdapter(this, R.layout.adapter_item, itemList);
        ListView listView = new ListView(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (adapter.getDeletePos() >= 0) {
                List<Item> tempItemList = adapter.getList();
                nameList.clear();
                for (Item item : tempItemList) {
                    nameList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = nameList.get(position);
            checkResult.setText(result);
            popupWindow.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        popupWindow = new PopupWindow(listView ,width, WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置点击外部区域可以取消popupWindow
        popupWindow.setOutsideTouchable(true);

        checkResult.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                popupWindow.showAsDropDown(checkResult);
            }
        });
    }

    public void save(View view) {
//        saveFile(checkResult.getText().toString());
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                SharedPreferences.Editor editor = preferences.edit();
                // 若有进行删除操作，更新nameList
                List<Item> tempItemList = adapter.getList();
                if (tempItemList.size() != nameList.size()) {
                    nameList.clear();
                    for (Item item : tempItemList) {
                        nameList.add(item.getName());
                    }
                }
                // 判断该输入框内容是否已存在，不存在则加入
                String currentCheckResult = checkResult.getText().toString();
                if (!currentCheckResult.equals("") && !nameList.contains(currentCheckResult)) {
                    nameList.add(currentCheckResult);
                }

                editor.putStringSet("checkResult", new HashSet<>(nameList));
                editor.apply();

                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                if (role.equals("检查人")) {
                    // 检查人提交表单
                    if (checkResult.getText().toString().equals("")) {
                        Toast.makeText(this, "请正确填写数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String url = Config.url + "/shlj/equipmentMaintenance/add_examiner";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("zys", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
//                                        checkResult.setText("");
//                                        comment.setText("");

                                        if (code.startsWith("2"))
                                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", formId);
                            map.put("examiner", name);
                            map.put("result", checkResult.getText().toString());
                            map.put("remarks", comment.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                } else {
                    // 操作人提交表单
                    String url = Config.url + "/shlj/equipmentMaintenance/add_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("zys", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        comment.setText("");

                                        if (code.startsWith("2"))
                                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(FacilityMaintainPlanActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            String facilityName = repairMethod.split(" ")[0];
                            String repairContent = repairMethod.split(" ")[1];

                            Map<String, String> map=new HashMap<>();
                            map.put("equipmentName", facilityName);
                            map.put("operator", name);
                            map.put("method", repairContent);
                            map.put("remarks", comment.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }
            })
            .show();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

}
